<?php
/**
 * Created by PhpStorm.
 * User: linhongzhao
 * Date: 18-5-12
 * Time: 下午2:47
 */
namespace EFrame\Cache\Pool;

use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;

class ArrayCachePool implements CacheItemPoolInterface
{
    /**
     * @var CacheItemInterface[]
     */
    protected static $pool = [];

    /**
     * ArrayCachePool constructor.
     * @param array $options
     */
    public function __construct($options = [])
    {
    }

    /**
     * @param string $key
     * @return CacheItemInterface
     */
    public function getItem($key)
    {
        if (
            isset(self::$pool[$key]) &&
            !empty($item = self::$pool[$key]) &&
            $item->isHit()
        ) {
            return self::$pool[$key];
        }
        return null;
    }

    /**
     * @param array $keys
     * @return array|\Traversable|void
     * TODO 待优化查找流程
     */
    public function getItems(array $keys = array())
    {
        $arr = [];
        foreach ($keys as $key) {
            $arr[$key] = $this->getItem($key);
        }
        return $arr;
    }

    public function hasItem($key)
    {
        if (isset(self::$pool[$key]) && !empty(self::$pool[$key])) {
            if (self::$pool[$key]->isHit()) {
                return true;
            }
            $this->deleteItem($key);
            return false;
        }
        return false;
    }

    public function clear()
    {
        self::$pool = [];
    }

    /**
     * @param string $key
     * @return bool
     * @throws \InvalidArgumentException The type of key must be a string!
     */
    public function deleteItem($key)
    {
        if (!is_string($key)) {
            throw new \InvalidArgumentException('The type of key must be a string!');
        }
        if (isset(self::$pool[$key])) {
            unset(self::$pool[$key]);
            return true;
        } else {
            return false;
        }
    }

    public function deleteItems(array $keys)
    {
        foreach ($keys as $key) {
            $this->deleteItem($key);
        }
    }

    public function save(CacheItemInterface $item)
    {
        self::$pool[$item->getKey()] = clone $item;
        return true;
    }

    /**
     * 延迟缓存，由于在内存中，因此不存在延迟缓存
     * @param CacheItemInterface $item
     * @return bool
     */
    public function saveDeferred(CacheItemInterface $item)
    {
        self::$pool[$item->getKey()] = clone $item;
        return true;
    }

    /**
     * 本类Cache不存在队列
     * @return bool
     */
    public function commit()
    {
        return true;
    }
}